<template>
    <el-dialog :model-value="props.isImport" :show-close="false" modal-class="customize-dialog" :append-to-body="true"
        :close-on-click-modal="false" align-center width="1000">
        <template #header="{ titleId, titleClass }">
            <div class="flex justify-between items-center dialog-header">
                <div class="flex items-center">
                    <h4 :id="titleId" :class="titleClass">文章导入</h4>
                    <span>您已发布 <el-text type="primary">{{ props.publishedArticle }}</el-text> 个文章，还能导入 <el-text
                            type="success">{{ props.publishArticle }}</el-text> 文章</span>
                </div>
                <svg-icon size="16px" icon-class="close-line" @click="closeDialog"></svg-icon>
            </div>
        </template>
        <div class="flex">
            <div class="flex-1"><el-input v-model="state.keyword" placeholder="请输入文章标题" clearable></el-input>
            </div>
            <el-button type="primary" :icon="Search" v-debounce="{ callback: handleSearch, delay: 300 }"
                class="ml-12px">搜索</el-button>
        </div>
        <el-table ref="tableRef" :data="state.tableData" :reserve-selection="true" max-height="650px"
            @selection-change="handleSelectionChange" class="w-full mt-16px">
            <el-table-column label="" type="selection" :selectable="selectable" align="center" width="40">
            </el-table-column>
            <el-table-column prop="ID" label="文章ID" align="center" width="100" />
            <el-table-column prop="Title" label="名称" align="center" />
            <el-table-column prop="time" label="创建时间" align="center" width="180">
                <template #default="scope">
                    {{ formatDate(scope.row.CreateTime) }}
                </template>
            </el-table-column>
            <el-table-column prop="time" label="修改时间" align="center" width="180">
                <template #default="scope">
                    {{ formatDate(scope.row.UpdateTime) }}
                </template>
            </el-table-column>
        </el-table>
        <div class="pl-10px pr-16px page-container flex justify-between items-center">
            <div class="flex items-center text-14px pt-12px">
                已选 <el-text type="success" class="!ml-5px !mr-5px"> {{ selectionData.length }} </el-text> 条数据 <el-button
                    type="primary" class="ml-12px" @click="batchImportArticle">确认导入</el-button>
            </div>
            <Pagination v-if="state.tableData.length > 0" v-model:total="state.page.total"
                v-model:page="state.page.curPage" v-model:limit="state.page.pageSizes" @pagination="handleQuery" />
        </div>
        
    </el-dialog>
</template>

<script setup lang="ts">
import { Search,SuccessFilled } from '@element-plus/icons-vue'
import Pagination from '@/components/Pagination/index.vue'
import { dateFormat } from '@/utils/date'
import { confirmMessageBox } from '@/utils/elMessageBox'
import { importArticleApi, searchArticleApi, batchImportArticleApi } from '@/api/b2b'

const props = defineProps<{
    isImport: boolean,
    publishedArticle: number,
    publishArticle: number
}>()

const emit = defineEmits(['closeDialog', 'updatePublishArticle'])

const state = reactive({
    tableData: [],
    keyword: '',
    page: {
        total: 0,
        curPage: 1,
        limit: 10,
        pageSizes: 10,
    },
    selectId: <number []>[]
})

const formatDate = computed(() => {
    return function (data: string) {
        return dateFormat(data, 'YYYY-MM-DD HH:mm:ss')
    }
})

const selectionData = ref<number[]>([])

const selectable = (row: any) => !state.selectId.includes(row.ID)

const tableRef = ref()
async function handleSearch() {
    await searchArticle()
}

function handleSelectionChange(rows: any) {
    selectionData.value = rows.map((row: any) => row.ID)
    emit('updatePublishArticle', selectionData.value.length)
}

function handleQuery() {
    importArticle()
}

async function importArticle() {
    const res: ResType = await importArticleApi()
    console.log(res)
    if (res.code === 200) {
        state.tableData = res.data
        state.page.curPage = res.page as number
        state.page.pageSizes = res.pagesize as number
        state.page.total = res.count as number

        nextTick(() => {
            res.data.forEach((item: any) => {
                if (item.IsShow === 1) {
                    selectionData.value.push(item.ID)
                    state.selectId.push(item.ID)
                }
            })
            refreshSelection()
        })
    }
}

async function searchArticle() {
    const res: ResType = await searchArticleApi({
        tk: state.keyword,
        pn: state.page.curPage,
        pagesize: state.page.pageSizes,
    })
    state.tableData = res.data
}

async function batchImportArticle() {
    //要将已经导入的id去除
    const set1 = new Set(state.selectId);
    const result = selectionData.value.filter(item => !set1.has(item))

    const res = await batchImportArticleApi({
        ids: result
    })
    if (res.code === 200) {
        selectionData.value = []
        state.selectId = []
        //关键词设置
        confirmMessageBox(SuccessFilled,res.message,'','',async() => {
            emit('closeDialog')
        })
    } else {
        ElMessage.error(res.message)
    }
}
function closeDialog() {
    emit('closeDialog')
}

// 新增一个方法，用于刷新表格的多选状态
function refreshSelection() {
    // 假设 tableRef 是 el-table 的 ref
    if (tableRef.value) {
        // 清除当前所有选中状态
        tableRef.value.clearSelection();
        // 遍历当前选中的 ID，重新设置选中状态
        selectionData.value.forEach((id: any) => {
            const row = state.tableData.find((item: any) => item.ID === id);
            if (row) {
                tableRef.value.toggleRowSelection(row, true);
            }
        });
    }
};

watchEffect(() => {
    if (props.isImport) {
        importArticle()
    }
})
</script>

<style scoped></style>